import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { View, Text, ListView } from 'react-native'
import { List, InputItem, Flex, Button, Picker, Modal, Popup } from 'antd-mobile'
import {createForm} from "rc-form";
import SearchMaterials from '../../widget/popup/SearchMaterials'
import { storageRecordList, storageRecordDetailList, signedContractList } from '../../libs/api'
import { RefreshListView, RefreshState } from '../../widget'
import { getOrganNo, getArchId, formatDate, isNotBlank, isBlank, getDomain} from '../../libs/Libs'
import { accDiv } from '../../libs/Acc'
import * as Libs from "../../libs/Libs";
import HTTP from '../../libs/HTTP'

const Item = List.Item
const alert = Modal.alert

class FormHeader extends Component {
  static propTypes = {
    onSearch: PropTypes.func
  }

  constructor(props) {
    super(props)
    this.seaTypes = [{
      value: 'single',
      label: '单支'
    }, {
      value: 'batch',
      label: '批次'
    }]
    this.isProducer = getDomain() == 'WINDER-PRODUCER'
    this.state = {
      producerOrganNo: undefined,
      producerInfo: [],
      brCode: '',
      brCodeName: '',
      seaSpecNum: '',
      chooseSeaType: ['single']
    }
  }

  componentDidMount() {
    if(this.isProducer) {
      this.setState({
        producerOrganNo: getOrganNo()
      })
    } else {
      HTTP.post(signedContractList(), {dealerOrganNo: Libs.getOrganNo()}, () => {}, (resp = []) => {
        let producerInfo = this.state.producerInfo
        resp.map((v, i) => {
          producerInfo.push({
            value: v['producerOrganNo'],
            label: v['producerOrganName']
          })
        })
        this.setState({
          producerInfo: producerInfo
        })
      })
    }
  }

  renderXX = () => {
    const { getFieldProps } = this.props.form;
    if(this.state.chooseSeaType[0] == 'single') {
      return (
        <InputItem
          {...getFieldProps("flowNo")}
        >流水号</InputItem>
      )
    } else {
      return (
        <InputItem
          {...getFieldProps("boxNo")}
        >箱号</InputItem>
      )
    }
  }
  render() {
    const { getFieldProps } = this.props.form;
    return (
      <View>
        <List renderHeader={() => "市场查询"}>
          <Picker
            data={this.seaTypes}
            value={this.state.chooseSeaType}
            onChange={(v) => {
              this.setState({
                chooseSeaType: v
              })
            }}
            cols={1}
          >
            <List.Item arrow="horizontal">类别</List.Item>
          </Picker>
          {
            !this.isProducer && (
              <Picker
                data={this.state.producerInfo}
                cols={1}
                onOk={v => {
                  this.setState({
                    producerOrganNo: v[0]
                  })
                }}
                {...getFieldProps('producerId')}
              >
                <List.Item arrow="horizontal">厂方</List.Item>
              </Picker>
            )
          }

          <InputItem
            value={this.state.brCodeName}
            onFocus={
              () => {
                Popup.show(<SearchMaterials
                  producerOrganNo={this.state.producerOrganNo}
                  invokeFill={(v) => {
                    this.setState({
                      brCode: v['specsCode'],
                      brCodeName: v['specsName'],
                      seaSpecNum: parseInt(v['specsNum'] || 1)
                    })
                  }}
                  onClose={() => Popup.hide()} />, { });
              }
            }
          >品名</InputItem>
          <InputItem
            {...getFieldProps("batchNum")}
          >批号</InputItem>
          {
            this.renderXX()
          }
          <Flex>
            <Flex.Item>
              <View style={{margin: 10}}>
                <Button onClick={this.onSearch}>查询</Button>
              </View>
            </Flex.Item>
          </Flex>
        </List>
      </View>
    )
  }

  onSearch = () => {
    const params = this.props.navigation.state.params || {}
    this.props.form.validateFields((err, values) => {
      let erCode = ''
      if(isBlank(this.state.brCode)) {
        alert('提示', '请选择品名');
        return false;
      }
      if(isBlank(values['batchNum'])) {
        alert('提示', '请输入批号')
        return false;
      }
      if(this.state.chooseSeaType[0] == 'single') {
        if(isBlank(values['flowNo'])) {
          alert('提示', '请输入流水号');
          return false;
        }
        if(isBlank(this.state.seaSpecNum)) {
          alert('提示', '此品牌规格错误')
          return false;
        }
        let flowNo = Math.ceil(accDiv(values['flowNo'], this.state.seaSpecNum))
        let boxNo = (Array(6).join('0') + flowNo).slice(-6)
        erCode = this.state.brCode + values['batchNum'] + boxNo
      } else {
        if(isBlank(values['boxNo'])) {
          alert('提示', '请输入箱号');
          return false;
        }
        erCode = this.state.brCode + values['batchNum'] + values['boxNo']
      }
      values['erCode'] = erCode
      values['isSingle'] = 'single' == this.state.chooseSeaType[0]
      values['recordType'] = params['recordType'] || 1
      if(this.isProducer) {
        values['producerOrganNo'] = getOrganNo()
      } else {
        values['producerOrganNo'] = this.state.producerOrganNo
        values['dealerOrganNo'] = getOrganNo()
      }
      values['archId'] = getArchId()
      this.props.onSearch(values)
    });
  }
}

const FormHeaderWrapper = createForm()(FormHeader)

export default class extends Component {
  constructor(props) {
    super(props)
    let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
    this.state = ({
      seaParams: {},
      isLoading: false, //是否正在加载
      currentPage: 0, //当前页
      dataSource: ds.cloneWithRows([]),　//数据源
      innerData: [] //内部数据
    })
  }

  listView: RefreshListView

  render = () => {
    return (
      <View>
        <FormHeaderWrapper onSearch={this.onSearch} {...this.props}/>
        <RefreshListView
          ref={(e) => this.listView = e}
          dataSource={this.state.dataSource}
          renderHeader={() =>
            <View></View>
          }
          renderRow={(rowData) => {
            return (
              this.renderCell(rowData)
            )
          }}
          onHeaderRefresh={() => this.requestData()}
          onFooterRefresh={() => this.requestData()}
        />
      </View>
    )
  }

  renderCell = (record) => {
    const linkCustomer = record['linkCustomer']
    const storageName = record['storageName']
    const actionTime = record['formattedActionTime']
    const erCodeName = record['erCodeName']
    const erBatchData = record['erBatchData']
    const erMaterialBox = record['erMaterialBox']
    const recordType = record['recordType']
    let recordTypeStr = ''
    if(recordType == 1) {
      recordTypeStr = '入库'
    } else if(recordType == 2) {
      recordTypeStr = '出库'
    } else if(recordType == 3) {
      recordTypeStr = '退货'
    }
    return (
      <Item>
        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
          <Text style={{fontWeight: 'bold', color: '#333333'}}>仓库: {storageName}</Text>
          <Text>{recordTypeStr + '/' + actionTime}</Text>
        </View>
        <View style={{height: 5}}></View>
        <View><Text>品名: {erCodeName} 批名: {erBatchData} 流水号: {erMaterialBox}</Text></View>
      </Item>
    )
  }

  onSearch = (values) => {
    this.setState({
      seaParams: values,
      currentPage: 0,
      innerData: []
    }, () => {
      this.requestData()
    })
  }


  requestData = () => {
    this.setState({isLoading: true})
    HTTP.post(storageRecordDetailList(), Object.assign({}, {
      page: this.state.currentPage
    },this.state.seaParams), () => {
      this.setState({isLoading: false})
    }, (resp) => {
      if(resp.data){
        if(resp.data.length == 0 && this.state.currentPage == 0) {
          alert('提示', '未查询到数据')
          this.setState(preState => {
            dataSource: preState.dataSource.cloneWithRows([])
          })
          return false;
        }
        this.setState(preState => {
          const newD = preState.innerData.concat(resp['data'])
          console.log('newD is {}', newD)
          return {
            innerData: newD,
            dataSource: preState.dataSource.cloneWithRows(newD),
            currentPage: preState.currentPage + 1
          }
        }, () => {
          if(resp.data.length == 0) {
            this.listView.endRefreshing(RefreshState.NoMoreData)
          } else {
            this.listView.endRefreshing(RefreshState.Idle)
          }
        })
      }
    })
  }

}
